<template>
  <div class="flash-sale-monitor">
    <el-card class="monitor-header">
      <div class="header-content">
        <h1>秒杀实时监控</h1>
        <div class="header-actions">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            @change="toggleAutoRefresh"
          />
          <el-button type="primary" @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            手动刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 实时数据概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon online">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ realTimeData.onlineUsers }}</div>
              <div class="card-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon qps">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ realTimeData.currentQPS }}</div>
              <div class="card-label">当前QPS</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon success">
              <el-icon><SuccessFilled /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ realTimeData.successRate }}%</div>
              <div class="card-label">成功率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon response">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ realTimeData.avgResponseTime }}ms</div>
              <div class="card-label">平均响应时间</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>QPS趋势图</h3>
              <el-select v-model="qpsTimeRange" @change="updateQPSChart">
                <el-option label="最近1小时" value="1h" />
                <el-option label="最近6小时" value="6h" />
                <el-option label="最近24小时" value="24h" />
              </el-select>
            </div>
          </template>
          <div ref="qpsChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>响应时间分布</h3>
              <el-select v-model="responseTimeRange" @change="updateResponseTimeChart">
                <el-option label="最近1小时" value="1h" />
                <el-option label="最近6小时" value="6h" />
                <el-option label="最近24小时" value="24h" />
              </el-select>
            </div>
          </template>
          <div ref="responseTimeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>错误率统计</h3>
            </div>
          </template>
          <div ref="errorRateChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>热门商品排行</h3>
            </div>
          </template>
          <div class="hot-products-list">
            <div 
              v-for="(product, index) in hotProducts" 
              :key="product.id"
              class="hot-product-item"
            >
              <div class="rank">{{ index + 1 }}</div>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-stats">
                  <span>请求数: {{ product.requests }}</span>
                  <span>成功率: {{ product.successRate }}%</span>
                </div>
              </div>
              <div class="product-trend">
                <el-icon :class="{ 'trend-up': product.trend > 0, 'trend-down': product.trend < 0 }">
                  <CaretTop v-if="product.trend > 0" />
                  <CaretBottom v-else />
                </el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态表格 -->
    <el-card class="system-status">
      <template #header>
        <div class="card-header">
          <h3>系统状态监控</h3>
          <div class="status-indicators">
            <el-tag :type="getSystemStatusType(systemStatus.redis)" size="small">
              Redis: {{ systemStatus.redis }}
            </el-tag>
            <el-tag :type="getSystemStatusType(systemStatus.database)" size="small">
              数据库: {{ systemStatus.database }}
            </el-tag>
            <el-tag :type="getSystemStatusType(systemStatus.mq)" size="small">
              消息队列: {{ systemStatus.mq }}
            </el-tag>
          </div>
        </div>
      </template>

      <el-table :data="systemMetrics" stripe>
        <el-table-column prop="metric" label="指标" width="200" />
        <el-table-column prop="current" label="当前值" width="150" />
        <el-table-column prop="threshold" label="阈值" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getMetricStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" min-width="200" />
      </el-table>
    </el-card>

    <!-- 告警日志 -->
    <el-card class="alert-logs">
      <template #header>
        <div class="card-header">
          <h3>告警日志</h3>
          <el-button type="danger" size="small" @click="clearAlerts">
            清空告警
          </el-button>
        </div>
      </template>

      <el-table :data="alertLogs" stripe max-height="300">
        <el-table-column prop="time" label="时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getAlertLevelType(scope.row.level)">
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="告警信息" min-width="300" />
        <el-table-column prop="source" label="来源" width="150" />
      </el-table>

      <el-empty v-if="alertLogs.length === 0" description="暂无告警信息" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, Connection, TrendCharts, SuccessFilled, Timer,
  CaretTop, CaretBottom
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(true)
const qpsTimeRange = ref('1h')
const responseTimeRange = ref('1h')

// 图表引用
const qpsChartRef = ref()
const responseTimeChartRef = ref()
const errorRateChartRef = ref()

// 图表实例
let qpsChart = null
let responseTimeChart = null
let errorRateChart = null

// 定时器
let refreshTimer = null

// 实时数据
const realTimeData = reactive({
  onlineUsers: 0,
  currentQPS: 0,
  successRate: 0,
  avgResponseTime: 0
})

// 热门商品
const hotProducts = ref([])

// 系统状态
const systemStatus = reactive({
  redis: '正常',
  database: '正常',
  mq: '正常'
})

// 系统指标
const systemMetrics = ref([])

// 告警日志
const alertLogs = ref([])

// 方法定义
// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchRealTimeData(),
      fetchHotProducts(),
      fetchSystemStatus(),
      fetchSystemMetrics(),
      fetchAlertLogs()
    ])
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

// 获取实时数据
const fetchRealTimeData = async () => {
  try {
    const res = await request.get('/flash-sale/monitor/realtime')
    if (res && res.data) {
      Object.assign(realTimeData, res.data)
    }
  } catch (error) {
    console.error('获取实时数据失败:', error)
  }
}

// 获取热门商品
const fetchHotProducts = async () => {
  try {
    const res = await request.get('/flash-sale/monitor/hot-products')
    if (res && res.data) {
      hotProducts.value = res.data
    }
  } catch (error) {
    console.error('获取热门商品失败:', error)
  }
}

// 获取系统状态
const fetchSystemStatus = async () => {
  try {
    const res = await request.get('/flash-sale/monitor/system-status')
    if (res && res.data) {
      Object.assign(systemStatus, res.data)
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
  }
}

// 获取系统指标
const fetchSystemMetrics = async () => {
  try {
    const res = await request.get('/flash-sale/monitor/system-metrics')
    if (res && res.data) {
      systemMetrics.value = res.data
    }
  } catch (error) {
    console.error('获取系统指标失败:', error)
  }
}

// 获取告警日志
const fetchAlertLogs = async () => {
  try {
    const res = await request.get('/flash-sale/monitor/alert-logs')
    if (res && res.data) {
      alertLogs.value = res.data
    }
  } catch (error) {
    console.error('获取告警日志失败:', error)
  }
}

// 切换自动刷新
const toggleAutoRefresh = (value) => {
  if (value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

// 开始自动刷新
const startAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  refreshTimer = setInterval(() => {
    refreshData()
  }, 5000) // 每5秒刷新一次
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initQPSChart()
    initResponseTimeChart()
    initErrorRateChart()
  })
}

// 初始化QPS图表
const initQPSChart = () => {
  if (qpsChartRef.value) {
    qpsChart = echarts.init(qpsChartRef.value)
    updateQPSChart()
  }
}

// 初始化响应时间图表
const initResponseTimeChart = () => {
  if (responseTimeChartRef.value) {
    responseTimeChart = echarts.init(responseTimeChartRef.value)
    updateResponseTimeChart()
  }
}

// 初始化错误率图表
const initErrorRateChart = () => {
  if (errorRateChartRef.value) {
    errorRateChart = echarts.init(errorRateChartRef.value)
    updateErrorRateChart()
  }
}

// 更新QPS图表
const updateQPSChart = async () => {
  if (!qpsChart) return

  try {
    const res = await request.get('/flash-sale/monitor/qps-data', {
      params: { timeRange: qpsTimeRange.value }
    })

    if (res && res.data) {
      const option = {
        title: {
          text: 'QPS趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: res.data.times
        },
        yAxis: {
          type: 'value',
          name: 'QPS'
        },
        series: [{
          data: res.data.values,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(64, 158, 255, 0.3)'
              }, {
                offset: 1, color: 'rgba(64, 158, 255, 0.1)'
              }]
            }
          },
          lineStyle: {
            color: '#409EFF'
          }
        }]
      }
      qpsChart.setOption(option)
    }
  } catch (error) {
    console.error('更新QPS图表失败:', error)
  }
}

// 更新响应时间图表
const updateResponseTimeChart = async () => {
  if (!responseTimeChart) return

  try {
    const res = await request.get('/flash-sale/monitor/response-time-data', {
      params: { timeRange: responseTimeRange.value }
    })

    if (res && res.data) {
      const option = {
        title: {
          text: '响应时间分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: res.data.times
        },
        yAxis: {
          type: 'value',
          name: '响应时间(ms)'
        },
        series: [{
          data: res.data.values,
          type: 'bar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#67C23A'
              }, {
                offset: 1, color: '#85CE61'
              }]
            }
          }
        }]
      }
      responseTimeChart.setOption(option)
    }
  } catch (error) {
    console.error('更新响应时间图表失败:', error)
  }
}

// 更新错误率图表
const updateErrorRateChart = async () => {
  if (!errorRateChart) return

  try {
    const res = await request.get('/flash-sale/monitor/error-rate-data')

    if (res && res.data) {
      const option = {
        title: {
          text: '错误率统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '错误类型',
          type: 'pie',
          radius: ['40%', '70%'],
          data: res.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      errorRateChart.setOption(option)
    }
  } catch (error) {
    console.error('更新错误率图表失败:', error)
  }
}

// 获取系统状态类型
const getSystemStatusType = (status) => {
  switch (status) {
    case '正常': return 'success'
    case '警告': return 'warning'
    case '异常': return 'danger'
    default: return 'info'
  }
}

// 获取指标状态类型
const getMetricStatusType = (status) => {
  switch (status) {
    case '正常': return 'success'
    case '警告': return 'warning'
    case '异常': return 'danger'
    default: return 'info'
  }
}

// 获取告警级别类型
const getAlertLevelType = (level) => {
  switch (level) {
    case '信息': return 'info'
    case '警告': return 'warning'
    case '错误': return 'danger'
    case '严重': return 'danger'
    default: return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 清空告警
const clearAlerts = () => {
  alertLogs.value = []
  ElMessage.success('告警日志已清空')
}

// 组件挂载
onMounted(() => {
  refreshData()
  initCharts()
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

// 组件卸载
onUnmounted(() => {
  stopAutoRefresh()
  if (qpsChart) {
    qpsChart.dispose()
  }
  if (responseTimeChart) {
    responseTimeChart.dispose()
  }
  if (errorRateChart) {
    errorRateChart.dispose()
  }
})
</script>

<style scoped>
.flash-sale-monitor {
  padding: 20px;
}

.monitor-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.card-icon.online {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.qps {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.response {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.hot-products-list {
  height: 320px;
  overflow-y: auto;
}

.hot-product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-stats {
  font-size: 12px;
  color: #909399;
}

.product-stats span {
  margin-right: 15px;
}

.product-trend {
  font-size: 18px;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.system-status {
  margin-bottom: 20px;
}

.status-indicators {
  display: flex;
  gap: 10px;
}

.alert-logs {
  margin-bottom: 20px;
}
</style>
